﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ButsaScraperLib.Caches
{
	/// <summary>
	/// Обобщенный кэш.
	/// Ключ и значение типа данных String.
	/// </summary>
	public class GenericCache
	{
		private readonly string _fileName;

		private readonly Dictionary<string, string> _cacheDictionary = new Dictionary<string, string>();

		public GenericCache(string fileName)
		{
			_fileName = fileName;
			LoadCache();
		}

		private void LoadCache()
		{
			string cachePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + _fileName;
			if (File.Exists(cachePath))
			{
				string cacheFileData = File.ReadAllText(cachePath);
				//все пары ключ/значение
				string[] cachePairs = cacheFileData.Split(new[] {'#'}, StringSplitOptions.RemoveEmptyEntries);
				foreach (var cachePair in cachePairs)
				{
					string[] keyValue = cachePair.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
					if (!_cacheDictionary.ContainsKey(keyValue[0]))
						_cacheDictionary.Add(keyValue[0], keyValue[1]);
				}
			}
		}

		public string GetFromCache(string key)
		{
			if (_cacheDictionary.ContainsKey(key))
				return _cacheDictionary[key];
			return String.Empty;
		}

		public void AddToCache(string key, string value)
		{
			if (_cacheDictionary.ContainsKey(key))
				_cacheDictionary[key] = value;
			else
				_cacheDictionary.Add(key, value);
		}

		public void Dispose()
		{
			FlushCacheInternal();
		}

		private void FlushCacheInternal()
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (var pair in _cacheDictionary)
			{
				stringBuilder.Append(String.Concat(pair.Key, '|', pair.Value, '#'));
			}
			string cachePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + _fileName;
			File.WriteAllText(cachePath, stringBuilder.ToString());
		}

		public void FlushCache()
		{
			FlushCacheInternal();
			LoadCache();
		}

		public List<string> GetAllKeys()
		{
			return _cacheDictionary.Keys.ToList();
		}

		public List<string> GetAllValues()
		{
			return _cacheDictionary.Values.ToList();
		}
	}
}
